/**
 * auth: zhuqingwen
 */
function ini_set() {
    ws = new WebSocket("ws://" + document.domain + ":7272");
    ws.onopen = function (){
    	var init_data = '{"type":"new_client", "token":"' + token + '"}';
    	ws.send(init_data);
    };
    ws.onmessage = onMessage;
    ws.onclose = function () {

    };
    ws.onerror = function () {
    	console.log('Connect Socketserver Failure');
    };

    //50秒发送一次心跳
    pingInterval(50000);
    getMessage(1);
}


function onMessage(response)
{
     var msg = evil(response.data);
     console.log(msg);
     switch (msg.msg_type)
     {

        case "new_client":
            if(msg.client_flag == 'all_client')
            {
                client_list = msg['client_list'];
                var user_list_box = $("#user-nav1-content");
                user_list_box.empty();
                var client = '';
                $.each(client_list, function(client_index, client_info){
                    client+='<li class="client-user-info chose-client" client_id="'+client_info['client_id']+'" from_user_id="'+client_info['user_id']+'" from_name="'+client_info['user_name']+'">';
                    client+='<img class="user-content-img" src="'+client_info['avatar']+'" >';
                    client+='<div class="user-content-div">';
                    client+='<p class="user-content-name">'+client_info['user_name']+'</p>';
                    client+='<img class="user-content-pic" src="'+getRoleIcon(client_info['user_role'])+'">';
                    client+='</div>';
                    client+='</li>';
                })
                user_list_box.append(client);
            }else{
                var client = '';
                client+='<li class="client-user-info chose-client" client_id="'+msg.client_id+'" from_user_id="'+msg.user_id+'" from_name="'+msg.user_name+'">';
                client+='<img class="user-content-img" src="'+msg.avatar+'" >';
                client+='<div class="user-content-div">';
                client+='<p class="user-content-name">'+msg.user_name+'</p>';
                client+='<img class="user-content-pic" src="'+getRoleIcon(msg.user_role)+'">';
                client+='</div>';
                client+='</li>';
                $("#user-nav1-content").append(client);
                online_client_length = $("#user-nav1-content li").length;
                if(online_client_length>100)
                {
                    $("#user-nav1-content li:last-child").remove();
                }
            }
            $('#online-count').text('('+msg.client_nums+')');
            $('#top-online-count').text(msg.client_nums);
            showService(msg);
            break;

        case 'message':
            showMessage(msg);
            break;

        case 'recall_msg':
            if(msg.from_token != token)
            {
                $(".client-user-info[msg_id='"+msg.msg_id+"']").remove();
            }
            break;

        case 'change_live':
            $('.center-nav-teacher').text('主讲：'+msg.teacher_name);
            $('.center-nav-img').attr('src',msg.teacher_avatar);
            if(msg.from_token != token)
            {
                 $("#live_teacher").val(msg.teacher_avatar);
            }
            break;

        case 'close_client':
            $("#user-nav1-content li[client_id='"+msg.client_id+"']").remove();
            $('#online-count').text('('+msg.client_nums+')');
            $('#top-online-count').text(msg.client_nums);

            $("#user-nav2-content li[client_id='"+msg.client_id+"']").remove();
            var service_length = $("#user-nav2-content li").length;
            $('#server-count').text('('+service_length+')'); 
            break;
     }
}


function sendMessage() {
    var content = $('#message_content').html(),
    to_client   = $('#to_client').val(),
    to_name     = $('#to_name').val();
    if($.trim(content).length>0)
    {
        $('.send').attr({"disabled":"disabled"});
        var message_data = {};
        message_data['type'] = 'message';
        message_data['to_client'] = to_client;
        message_data['to_name']   = to_name;
        message_data['content']   = content;
        message_data['token']     = token;
        ws.send(JSON.stringify( message_data ));
        setInterval(function()
        {
            $('.send').removeAttr("disabled");
        },1500);
        resetForClient();
    }else{
        alert('请输入内容！');
    }
}

function getMessage(page)
{
    $.ajax({
        type: "POST",
        url: "/index/getMessage",
        data: {room_id:room_id, page:page},
        dataType: "json", 
        success: function(response){
            if(!response)return false;
            $.each(response, function(client_index, client_info){
                showMessage(client_info);
            })          
        }
    });
}

var page_up = 1;
$('.get_more_msg').click(function(){
    var page = $(this).attr('data-page');
    page_up++;
    getMessage(page_up);
 })

function showMessage(data)
{
    var msg = '';
    msg+='<li class="client-user-info" msg_cache_index="'+data.msg_cache_index+'" from_user_id="'+data.from_user_id+'" msg_id="'+data.msg_id+'" from_token="'+data.from_token+'">';
    msg+='<img class="meet-img" src="'+data.from_avatar+'">';
    msg+='<img class="meet-pic" src="'+getRoleIcon(data.user_role)+'">';
    msg+='<a href="javascript:void(0)"><span class="meet-name chose-client" from_user_id="'+data.from_user_id+'" from_name="'+data.from_name+'">'+data.from_name+'</span></a>';
    msg+='<span class="meet-time">'+data.date+'</span>';
    msg+='<div class="meet-msg">'+data.content+'</div>';
    msg+='<div class="message-menu">';
    msg+='<ul>';
    if(data.from_token == token)
    {
        msg+='<li><button class="layui-btn layui-btn-xs recall_msg">撤回</button></li>';
    }else{
        if(data.is_examine == 1)
        {
            msg+='<li><button class="layui-btn layui-btn-normal layui-btn-xs layui-btn-disabled">已审核</button></li>';
        }else{
            msg+='<li><button class="layui-btn layui-btn-normal layui-btn-xs audit_msg">审核</button></li>';
        }
        msg+='<li><button class="layui-btn layui-btn-xs power_recall_msg" >撤回</button></li>';
        if(data.speak_state == 1)
        {
            msg+='<li><button class="layui-btn layui-btn-normal layui-btn-xs layui-btn-warm operate_nospeak">禁言</button></li>';
        }else{
            msg+='<li><button class="layui-btn layui-btn-normal layui-btn-xs layui-btn-normal relieve_nospeak">解禁</button></li>';
        }
        msg+='<li><button class="layui-btn layui-btn-xs layui-btn-danger out_client">踢出</button></li>';
    }
    msg+='</ul>';
    msg+='</div>';  
    msg+='<div style="clear: both;"></div>';
    msg+='</li>';
    $('.right-msg-meet').append(msg);
    scrollBottom();
}

//显示客服
function showService(msg)
{
    var service = '';
    $.each(msg.service_list, function(client_index, client_info){
        service+='<li service_id="'+client_info['service_id']+'" client_id="'+client_info['client_id']+'">';
        service+='<img class="user-content-img" src="'+client_info['service_avatar']+'" >';
        service+='<div class="user-content-div">';
        service+='<p class="user-content-name">'+client_info['service_name']+'</p>';
        service+='<img class="user-content-pic" src="/static/images/kefu.png">';
        service+='<a href="javascript:void(0)" class="qq-chat chat_online_server" service_id="'+client_info['service_id']+'">';
        service+='<div class="QQ">在线客服</div>';
        service+='</a>';
        service+='</div>';
        service+='</li>';
    })
    $('#user-nav2-content').append(service);
    var service_length = $("#user-nav2-content li").length;
    $('#server-count').text('('+service_length+')'); 
}


layui.use(['layer','form', 'upload'], function(){
    var layer = layui.layer, form   = layui.form, upload = layui.upload;
    //撤回消息
    $(document).on('click','.recall_msg',function () {
        var msg_cache_index = $(this).parents('.client-user-info').attr('msg_cache_index'),
        from_user_id   = $(this).parents('.client-user-info').attr('from_user_id'),
        msg_id         = $(this).parents('.client-user-info').attr('msg_id'),
        from_token     = $(this).parents('.client-user-info').attr('from_token');
        var this_element = $(this);
        if(msg_cache_index)
        {
            $.ajax({
                type: "POST",
                url: "/index/recall_message",
                data: {msg_cache_index:msg_cache_index, from_user_id:from_user_id, from_token:from_token, msg_id:msg_id},
                dataType: "json", 
                success: function(response){
                   if(response.code == 200)
                   {
                        this_element.text('已撤回');
                        this_element.addClass('layui-btn-disabled');
                   }else{
                        layer.msg(response.msg);
                        return false;
                   }           
                }
            });
        }
    })
    //管理员撤回用户消息 
    $(document).on('click','.power_recall_msg',function () {
        var msg_cache_index = $(this).parents('.client-user-info').attr('msg_cache_index'),
        from_user_id   = $(this).parents('.client-user-info').attr('from_user_id'),
        msg_id         = $(this).parents('.client-user-info').attr('msg_id'),
        from_token     = $(this).parents('.client-user-info').attr('from_token');
        var this_element = $(this);
        if(msg_cache_index)
        {
            $.ajax({
                type: "POST",
                url: "/index/power_recall_message",
                data: {msg_cache_index:msg_cache_index, from_user_id:from_user_id, from_token:from_token, msg_id:msg_id},
                dataType: "json", 
                success: function(response){
                   if(response.code == 200)
                   {
                        this_element.text('已撤回');
                        this_element.addClass('layui-btn-disabled');
                   }else{
                        layer.msg(response.msg);
                        return false;
                   }           
                }
            });
        }
    })
    //审核消息
    $(document).on('click','.audit_msg',function () {
        var msg_cache_index = $(this).parents('.client-user-info').attr('msg_cache_index'),
        from_user_id   = $(this).parents('.client-user-info').attr('from_user_id'),
        msg_id         = $(this).parents('.client-user-info').attr('msg_id'),
        from_token     = $(this).parents('.client-user-info').attr('from_token');
        var this_element = $(this);
        if(msg_cache_index)
        {
            $.ajax({
                type: "POST",
                url: "/index/audit_message",
                data: {msg_cache_index:msg_cache_index, from_user_id:from_user_id, from_token:from_token, msg_id:msg_id},
                dataType: "json", 
                success: function(response){
                   if(response.code == 200)
                   {
                        this_element.text('已审核');
                        this_element.addClass('layui-btn-disabled');
                   }else{
                        layer.msg(response.msg);
                        return false;
                   }           
                }
            });
        }
    })
    //禁言
    $(document).on('click','.operate_nospeak',function () {
        var from_token   = $(this).parents('.client-user-info').attr('from_token');
        var this_element = $(this);
        if(from_token)
        {
            $.ajax({
                type: "POST",
                url: "/index/prohibitSpeak",
                data: {from_token:from_token},
                dataType: "json", 
                success: function(response){
                   if(response.code == 200)
                   {
                        this_element.text('解禁');
                        this_element.removeClass('layui-btn-warm');
                        this_element.addClass('layui-btn-normal');
                        this_element.addClass('relieve_operate_nospeak');
                   }else{
                        layer.msg(response.msg);
                        return false;
                   }           
                }
            });
        }
    })
    //解除禁言
    $(document).on('click','.relieve_operate_nospeak',function () {
        var from_token   = $(this).parents('.client-user-info').attr('from_token');
        var this_element = $(this);
        if(from_token)
        {
            $.ajax({
                type: "POST",
                url: "/index/releaseSpeak",
                data: {from_token:from_token},
                dataType: "json", 
                success: function(response){
                   if(response.code == 200)
                   {
                        this_element.text('禁言');
                        this_element.removeClass('layui-btn-normal');
                        this_element.addClass('layui-btn-warm');
                        this_element.addClass('operate_nospeak');
                   }else{
                        layer.msg(response.msg);
                        return false;
                   }           
                }
            });
        }
    })
    //踢出客户
    $(document).on('click','.out_client',function () {
        var from_token   = $(this).parents('.client-user-info').attr('from_token');
        var this_element = $(this);
        if(from_token)
        {
            $.ajax({
                type: "POST",
                url: "/index/outClient",
                data: {from_token:from_token},
                dataType: "json", 
                success: function(response){
                   if(response.code == 200)
                   {
                        this_element.text('已踢出');
                        this_element.addClass('layui-btn-warm');
                        this_element.addClass('layui-btn-disabled');
                   }else{
                        layer.msg(response.msg);
                        return false;
                   }           
                }
            });
        }
    })
    //切换直播讲师
    $('#change_live_info').click(function()
    {
        var teacher_name = $('#live_teacher option:selected').text(),
            teacher_avatar = $('#live_teacher option:selected').val();
        $.ajax({
            type: "POST",
            url: "/index/change_live",
            data: {teacher_name:teacher_name, teacher_avatar:teacher_avatar, token:token},
            dataType: "json", 
            success: function(response){
               if(response.code == 200)
               {
                    layer.msg('更改成功');
                    return false;
               }else{
                    layer.msg(response.msg);
                    return false;
               }           
            }
        });
    })
    //发送图片
    upload.render({
          elem: '#btnImage' //绑定元素
          ,url: "/index/upload_img" //上传接口
          ,field:'file'
          ,accept : 'images'
          ,exts : 'jpg|png|gif|jpeg'
          ,size :40960 //最大4M
          ,multiple :false //不允许多图上传
          ,before: function(obj){
                this.data={room_id:room_id};
                layer.load(); //上传loading
            }
          ,done: function(res){
            //上传完毕回调
            var img_msg = '<img src="'+res.data.src+'" style="width:100%;height:180px" class="message_img">'
            $('#message_content').html(img_msg);
            layer.closeAll("loading");
            layer.msg(res.msg);
          }
          ,error: function(){
            layer.msg('上传失败');
          }
    });

    //开启自动发言
    var set_timer;
    $('.start_auto_speak').click(function()
    {
        var speak_role = $('#speak_role option:selected').val();
        var speak_time = $('#speak_time option:selected').val();
        var start_speak = '{"type":"start_auto_speak", "speak_role":"'+speak_role+'", "token":"' + token + '"}';
        set_timer = setInterval(function()
        {
            ws.send(start_speak);
        },speak_time)
        
    })
    //关闭自动发言
    $('.stop_auto_speak').click(function()
    {
        clearInterval(set_timer);
    })
})

//单独对某个客户发送消息
$(document).on('click','.chose-client',function () {
    var user_id = $(this).attr('from_user_id');
    var from_name = $(this).attr('from_name');
    $('#to_client').val(user_id);
    $('.dj').html(from_name);
    $('#to_name').val(from_name);
})

$('.dj').click(function()
{
    $('#message_content').val('');
    $('#to_client').val('all');
    $('#to_name').val('大家');
    $('.dj').text('大家');
})

/*
*打开客服窗口
 */
$(document).on('click','.chat_online_server',function () {
    var service_id = $(this).attr('service_id'),
        service_avatar = $(this).parent().parent().find('.user-content-img').attr('src'),
        service_name = $(this).parent().find('.user-content-name').text();
    layer.open({
        area: ['600px', '522px'],
        scrollbar: false,
        title: false,
        skin: 'layui-layer-setmybg',
        type:2, 
            content: ['/services/open_service?token='+token+'&service_id='+service_id+'&service_name='+service_name+'&service_avatar='+service_avatar,'no'] 
    });
})



function evil(fn) {
    var Fn = Function;  
    return new Fn('return ' + fn)();
}

//定时发送心跳数据
function pingInterval(time = 50000)
{
    setInterval(function () {
      var ping = '{"type":"ping","token":"'+token+'"}';
      ws.send(ping);
    }, time);
}

function resetForClient()
{
    $('#message_content').html('');
    $('#to_user_client').val('all');
    $('#to_user_name').val('大家');
    $('#to_client').text('大家');
    disableSend();
}

function disableSend()
{
    $('.send').attr("disabled", true); 
    $('#message_content').attr("contenteditable", false); 
    setTimeout('reinstatementSend()', 2000); 
}

function reinstatementSend()
{
    $('.send').removeAttr("disabled");
    $('#message_content').attr("contenteditable", true); 
}

function scrollBottom()
{
    $('.right-msg-meet').scrollTop($('.right-msg-meet')[0].scrollHeight);
    msg_length = $(".client-user-info").length;
    if(msg_length>40)
    {
        $('.client-user-info:first').remove();
    }
}